const express = require("express");
const router = express.Router();
const db = require("../sql");

// 创建或更新地址
router.post("/createOrUpdate", async (req, res) => {
  const { id, userId, contacts, address, phone, isDefault } = req.body;

  // 如果isDefault为1，则先更新其他所有地址为非默认
  if (isDefault) {
    const unsetDefaultSql = "UPDATE address SET isDefault = 0 WHERE userId = ?";
    await db.query(unsetDefaultSql, [userId]);
  }
  await insertOrUpdateAddress();
  async function insertOrUpdateAddress() {
    const sql = `
                INSERT INTO address (id, userId, contacts, address, phone, isDefault)
                VALUES (?, ?, ?, ?, ?, ?)
                ON DUPLICATE KEY UPDATE
                userId = VALUES(userId),
                contacts = VALUES(contacts),
                address = VALUES(address),
                phone = VALUES(phone),
                isDefault = VALUES(isDefault);
            `;

    await db.query(sql, [id, userId, contacts, address, phone, isDefault]);
  }
  res.json({ success: true, message: "Address created or updated" });
});

// 删除地址
router.delete("/:id", (req, res) => {
  const sql = "DELETE FROM address WHERE id = ?";
  let result = db.query(sql, [req.params.id]);
  res.send({
    data: result,
    success: true,
  });
});

// 设置默认地址
router.patch("/setDefault/:id", (req, res) => {
  const sql =
    "UPDATE address SET isDefault = 0; UPDATE address SET isDefault = 1 WHERE id = ?";

  let result = db.query(sql, [req.params.id]);
  res.send({
    data: result,
    success: true,
  });
});

// 获取所有地址
router.get("/getAll/:userId", async (req, res) => {
  const sql = "SELECT * FROM address where userId = ?";
  let result = await db.query(sql, [req.params.userId]);
  res.send({
    data: result,
    success: true,
  });
});

module.exports = router;
